package com.power.test.model.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.Instant;
import java.util.Date;

/**
 * Date 反序列化器
 */
public class DateDeserializer extends JsonDeserializer<Date> implements ContextualDeserializer {
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        try {
            //时间戳字符串
            String value = jsonParser.getText();
            if (StringUtils.isBlank(value)) return null;
            //时间戳
            Long time = new Long(value);
            Instant instant;
            if (value.length() == 10) {
                //10位时间戳 秒级 1612627200
                return new Date(time * 1000);
            } else {
                //13位时间戳 毫秒级 1612627200000
                return new Date(time);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        return new DateDeserializer();
    }
}
